package shayu.cat.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import dm.jdbc.util.StringUtil;
import io.renren.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import shayu.cat.feign.ProductFeignService;
import shayu.cat.interceptor.CartInterceptor;
import shayu.cat.service.CartService;
import shayu.cat.to.UserInfoTo;
import shayu.cat.vo.CartItemVo;
import shayu.cat.vo.CartVo;
import shayu.cat.vo.SkuInfoVo;
import shayu.exception.CartExceptionHandler;
import springfox.documentation.spring.web.json.Json;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service("CartService")
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ThreadPoolExecutor executor;

    @Autowired
    private ProductFeignService productFeignService;

    private final String CART_PREFIX = "shayu:cart";

    @Override
    public CartItemVo addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        String res = (String) cartOps.get(skuId.toString());

        if (StringUtil.isEmpty(res)) {
            //  2. 商品添加到购物车
            CartItemVo cartItemVo = new CartItemVo();

            R skuInfo = productFeignService.info(skuId);

            // 1.远程查询当前要添加的商品的信息
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                if (skuInfo.getCode() == 0) {
                    SkuInfoVo data = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                    });
                    cartItemVo.setCheck(true);
                    cartItemVo.setCount(1);
                    cartItemVo.setSkuId(skuId);
                    cartItemVo.setImage(data.getSkuDefaultImg());
                    cartItemVo.setPrice(data.getPrice());
                    cartItemVo.setTitle(data.getSkuTitle());
                }
            }, executor);

            // 2. 远程查询sku组合信息
            CompletableFuture<Void> getSkuSaleAttrValues = CompletableFuture.runAsync(() -> {
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItemVo.setSkuAttr(skuSaleAttrValues);
            }, executor);

            CompletableFuture.allOf(getSkuInfoTask, getSkuSaleAttrValues).get();
            String s = JSON.toJSONString(cartItemVo);
            cartOps.put(skuId.toString(), s);
            return cartItemVo;
        } else {
            // 购物车有此商品 ，修改数量
            CartItemVo cartItemVo = JSON.parseObject(res, CartItemVo.class);
            cartItemVo.setCount(cartItemVo.getCount() + num);
            cartOps.put(skuId.toString(), JSON.toJSONString(cartItemVo));
            return cartItemVo;
        }
    }

    // 获取购物车登录信息
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = "";
        if (userInfoTo.getUserId() != null) {
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);

        return operations;
    }

    // TODO 可能需要在优化
    @Override
    public CartVo getCart() {

        CartVo cart = new CartVo();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        // 没登录
        if (userInfoTo.getUserId() != null) {
            // 登录
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            // 3,获取登录后的购物车数据
            List<CartItemVo> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        } else {
            //  没登陆
            String userKey = CART_PREFIX + userInfoTo.getUserKey();
            BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(userKey);
            List<Object> values = operations.values();
            if (values != null && values.size() > 0) {
                List<CartItemVo> collect = values.stream().map((obj) -> {
                    return new CartItemVo();
                }).collect(Collectors.toList());
                cart.setItems(collect);
            }
        }
        return cart;
    }

    @Override
    public void clearCart(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer checked) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItemVo cartItem = getCartItem(skuId);
        cartItem.setCheck(checked==1?true:false);
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),s);
    }

    @Override
    public void changeItemCount(Long skuId, Integer num) {
        CartItemVo cartItem = getCartItem(skuId);
        cartItem.setCount(num);

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(),JSON.toJSONString(cartItem));
    }

    @Override
    public CartItemVo getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String redisValues = (String) cartOps.get(skuId.toString());
        CartItemVo cartItemVo = JSON.parseObject(redisValues, CartItemVo.class);
        return cartItemVo;

    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        cartOps.delete(skuId.toString());
    }

    // 获取用户购物车的项
    @Override
    public List<CartItemVo> getUserCartItems() {
        List<CartItemVo> cartItemVos = new ArrayList<>();
        // 获取用户当前信息
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId()==null){
            // 没登录
            return null;
        }else{
            // 获取用户购物车的项
            String cartKey = CART_PREFIX+userInfoTo.getUserId();
            List<CartItemVo> cartItems = getCartItems(cartKey);
            if(cartItems==null){
                // 说明没有
                throw new CartExceptionHandler();
            }
            cartItemVos = cartItems.stream().filter(items -> items.getCheck()).map(item -> {
                // 获取最新价格 远程调用
                BigDecimal price = productFeignService.getPrice(item.getSkuId());
                item.setPrice(price);
                return item;
            }).collect(Collectors.toList());


        }
        return cartItemVos;
    }

    private List<CartItemVo> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if (values != null && values.size() > 0) {
            List<CartItemVo> collect = values.stream().map((obj) -> {
                String str = (String) obj;
                CartItemVo cartItemVo = JSON.parseObject(str, CartItemVo.class);
                return cartItemVo;
            }).collect(Collectors.toList());
            return collect;
        }else{

        }
        return null;
    }



}
